package com.allen.app.common.config;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@AllArgsConstructor
@Slf4j
public class CommonConfig {

    private CommonProperties properties;

    @Bean
    public Snowflake snowflake(){
        log.info("\t===>>\t[CommonConfig] snowflake initializing......");
        //分布式id 19位数
        return IdUtil.getSnowflake(properties.getWorkerId(),properties.getDataCenterId());
    }

    /**
     * 解决Jackson导致Long型数据精度丢失问题
     *
     * @return org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer
     * @author Limiaojun
     * @date 2020/1/9 11:42
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        log.info("\t===>>\t[CommonConfig] jackson2ObjectMapperBuilderCustomizer initializing......");
        return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder
            .serializerByType(Long.class, new JsonSerializer<Long>() {
                @Override
                public void serialize(Long value, JsonGenerator jsonGenerator, SerializerProvider provider)
                    throws IOException {
                    if (value.toString().length() > 10) {
                        jsonGenerator.writeString(value.toString());
                    } else {
                        jsonGenerator.writeNumber(value);
                    }
                }
            });

    }
}
